package com.ericsson.enap.modules.ebmLog.task.vgc;

import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.config.datasource.DynamicDataSourceContextHolder;
import com.ericsson.config.enums.DataSourceType;
import com.ericsson.enap.modules.ebmLog.entity.vgc.VgcEbmEventVO;
import com.ericsson.enap.modules.ebmLog.entity.vgc.VgcEbmTaskParam;
import com.ericsson.enap.modules.ebmLog.entity.vgc.amf.PagingSub;
import jodd.bean.BeanUtil;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

import static com.ericsson.enap.modules.ebmLog.utils.VgcEbmLogUtil.*;
import static java.util.stream.Collectors.counting;

/**
 * @description: 5gc 核心功能，统计csv并计算出需要的数据，最后入库
 * @author: wangjingshi
 * @create: 2021-11-10 15:02
 */
public class VgcEbmStatisticAndLoadTask implements Runnable{

    private Logger log = LoggerUtils.Logger(LogFileName.VgcEbmLogJob);
    private CountDownLatch latch;
    private Map<String, VgcEbmEventVO> map;
    private VgcEbmTaskParam vgcEbmTaskParam;

    public VgcEbmStatisticAndLoadTask(CountDownLatch latch,Map<String, VgcEbmEventVO> map,VgcEbmTaskParam vgcEbmTaskParam) {
        this.latch = latch;
        this.map = map;
        this.vgcEbmTaskParam = vgcEbmTaskParam;
    }

    @Override
    public void run() {
        CountDownLatch inner_latch = new CountDownLatch(map.size());
        for(Map.Entry<String,VgcEbmEventVO> entry:map.entrySet()){
            VgcEbmCoreTask task = new VgcEbmCoreTask(vgcEbmTaskParam,entry.getKey(),inner_latch);
            new Thread(task).start();
        }
        this.dealAmfChart();
        try {
            inner_latch.await();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        } finally {
            latch.countDown();
        }
    }

    private void dealAmfChart() {
        try {
            String localPath = vgcEbmTaskParam.getLocalPath();
            localPath = "C:\\Users\\ws_wa\\Desktop\\csv\\";
            String[] dirs = new File(localPath).list((x, y)-> y.endsWith("amf_paging.csv"));
            List<PagingSub> allList = new ArrayList<>();
            List<PagingSub> errorList = new ArrayList<>();
            PagingSub p,e;
            for(int i=0;i<dirs.length;i++){
                InputStreamReader read = new InputStreamReader(new FileInputStream(localPath + dirs[i]));
                BufferedReader bufferedReader = new BufferedReader(read);
                String line;
                String[] lineStr;
                int count = 0;
                while((line = bufferedReader.readLine())!=null) {
                    count++;
                    if(count==1){
                        continue;
                    }
                    lineStr = line.split(",",-1);
                    p = new PagingSub();
                    p.setEvent_result(1);
                    p.setDuration(getDuration(lineStr[5]));
                    p.setPaging_attempts(getPaging_attempts(lineStr[17]));
                    p.setTotal_no_of_paged_ngran_node(getTotal_no_of_paged_ngran_node(lineStr[19]));
                    allList.add(p);
                    if(lineStr[0].equals("success")){
                        continue;
                    }
                    e = new PagingSub();
                    e.setEvent_result(0);
                    e.setDuration(getDuration(lineStr[5]));
                    e.setPaging_attempts(getPaging_attempts(lineStr[17]));
                    e.setTotal_no_of_paged_ngran_node(getTotal_no_of_paged_ngran_node(lineStr[19]));
                    errorList.add(e);
                }
                bufferedReader.close();
                read.close();
            }
            String tableName = vgcEbmTaskParam.getDateTime().substring(0,10).replaceAll("-", "_") + "_" +
                    vgcEbmTaskParam.getNetId() + "_amf_paging_sub";
            String time = vgcEbmTaskParam.getDateTime().substring(11);
            String[] dimensionArr = {"paging_attempts","duration","total_no_of_paged_ngran_node"};
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
            for(int i = 0; i< dimensionArr.length; i++){
                String k_name = dimensionArr[i];
                Map<PagingSub, Long> allMap = allList.stream().collect(Collectors.groupingBy(x -> {
                    Object property = BeanUtil.pojo.getProperty(x, k_name);
                    x.setK_key(property.toString());
                    return x;
                }, counting()));
                String[] arr = vgcEbmTaskParam.getEbmParam().getPagingChart().get(k_name).split(",");
                for(String str:arr){
                    boolean f = false;
                    for(Map.Entry<PagingSub, Long> entry:allMap.entrySet()){
                        if(entry.getKey().getK_key().equals(str)){
                            vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub2(str,1,time,tableName,k_name,entry.getValue());
                            f = true;
                        }
                    }
                    if(!f){
                        vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub2(str,1,time,tableName,k_name,0L);
                    }
                }
                /*if(allMap.size()>0){
                    vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub(allMap,time,tableName,k_name);
                }*/
                Map<PagingSub, Long> errorMap = errorList.stream().collect(Collectors.groupingBy(x -> {
                    Object property = BeanUtil.pojo.getProperty(x, k_name);
                    x.setK_key(property.toString());
                    return x;
                }, counting()));
                /*if(errorMap.size()>0){
                    vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub(errorMap,time,tableName,k_name);
                }*/
                for(String str:arr){
                    boolean f = false;
                    for(Map.Entry<PagingSub, Long> entry:errorMap.entrySet()){
                        if(entry.getKey().getK_key().equals(str)){
                            vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub2(str,0,time,tableName,k_name,entry.getValue());
                            f = true;
                        }
                    }
                    if(!f){
                        vgcEbmTaskParam.getVgcEbmLogMapper().insertPagingSub2(str,0,time,tableName,k_name,0L);
                    }
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}
